//
//  LYOauthViewController.swift
//  Sina_Weibo2
//
//  Created by Elsevier on 16/5/14.
//  Copyright © 2016年 Yang Lu. All rights reserved.
//

import UIKit
import SVProgressHUD

class LYOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = GlobalBKGColor
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.title = "登陆"
        
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        LYPrint(items: "urlString: \(urlString)")
        LYPrint(items: url)
        
        
         webView.loadRequest( NSURLRequest(URL:url!))
        
//        SVProgressHUD.showWithStatus("正在加载...")
    }
    
    // MARK: - Setter & Getter 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    @objc private func autoFill() {
        let jsString = "document.getElementById('userId').value='13632263233';document.getElementById('passwd').value='luyang0228';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!
        
        if !url.absoluteString.hasPrefix(redirect_uri) {
            // 只要不是授权回调地址,是新浪的界面,就让他去加载
            return true
        } else {
            // 是授权回调地址,点击的是取消或授权,不让他去加载,我们自己来做一些事情
            // URL的query: ?后面的东西
            let query = url.query!
            //            CZPrint(items: "query: \(query)")
            let codeString = "code="
            
            if query.hasPrefix(codeString) {
                // 如果query 是以 code=开头表示点击的授权按钮
                // 从query中截取code的值,substringFromIndex从指定位置截取到最后
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                LYPrint(items: "code: \(code)")
                
                /// 加载AccessToken,字典转模型,模型保存到沙盒
                LYUserAccountViewModel.sharedInstance.loadAccessToken(code, callback: { (error) -> () in
                    if error != nil {
                        // 出现了错误
                        LYPrint(items: "出现了错误: \(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力...")
                        
                        // 延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    } else {
                        // 没有错误
                        self.close()
                    }
                })
            } else {
                // 点击的是取消按钮
                close()
            }
            
            return false
        }
    }
}


extension LYOauthViewController:UIWebViewDelegate{
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
}

